'''
介绍：此代码实现了对cv2.matchTemplate的模仿，同一张图片运行后得到的minval, maxval, minloc, maxloc数值大小基本类似。
说明：需将图片转换为float或double以提高运算精度和避免超出数据范围
'''
import cv2
import numpy as np


image = cv2.imread("images\\t001.jpg")
templ = cv2.imread("eye.jpg")


def matchTemplate(img,tpl,method):
    img = img.astype('float')
    tpl = tpl.astype('float')

    if method == 0:
        def func(a,b):
            return np.sum((a-b)**2)

    elif method == 3:
        def func(a,b):
            print(a)
            print(b)
            return np.sum(a*b)/((np.sum(a**2)*np.sum(b**2))**0.5)

    global h
    global w
    h = tpl.shape[0]
    w = tpl.shape[1]

    result_h = img.shape[0] - tpl.shape[0] + 1
    result_w = img.shape[1] - tpl.shape[1] + 1
    result = np.zeros((result_h,result_w))

    for y in range(result_h):
        for x in range(result_w):
            result[y,x] = func(tpl,img[y:y+h,x:x+w])
    return result

result = matchTemplate(image,templ,method=3)


minval, maxval, minloc, maxloc = cv2.minMaxLoc(result)
output = cv2.rectangle(image, maxloc, (maxloc[0] + w, maxloc[1] + h), (0, 200, 0), 2)
print(result.shape)
cv2.imshow('1',output)
cv2.imshow('0',result)
cv2.waitKey()
cv2.destroyAllWindows()